package dk.itu.spvc.tourtracker.gui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class CreatePinActivity extends Activity implements OnClickListener {

	// CONST
	
	public final static String ACTION_CREATE = "create";
	public final static String ACTION_EDIT = "edit";
	
	// PRIVATE FIELDS
	
	// Debug
	//private static final String TAG = "TourTracker";
	//private static final boolean D = true;
	
	EditText pinNoteText;

	// OVERRIDES
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_pin);
	}

	@Override
	protected void onStart() {
		super.onStart();

		((Button) findViewById(R.id.SavePinButton)).setOnClickListener(this);
		Button buttonDelete = ((Button) findViewById(R.id.DeletePinButton));
		TextView textView = ((TextView) findViewById(R.id.TextView));
		pinNoteText = (EditText) findViewById(R.id.PinNoteText);
		
		int pointIndex = this.getIntent().getIntExtra("pointIndex", -1);		
		if (pointIndex == -1) {
			// New pin			
			buttonDelete.setVisibility(View.GONE);
			textView.setText("Add text note");
		}
		else {
			// Existing pin
			buttonDelete.setVisibility(View.VISIBLE);
			buttonDelete.setOnClickListener(this);
			textView.setText("Edit text note");
			if(this.getIntent().hasExtra("pinNoteText")) {
				pinNoteText.setText(this.getIntent().getStringExtra("pinNoteText"));	
			}
		}		
	}

	// EVENTS
	
	public void onClick(View v) {

		if (v == findViewById(R.id.SavePinButton)) {

			String action = this.getIntent().getStringExtra("action");
			String note = pinNoteText.getText().toString();
			
			Intent intent = new Intent();
			intent.putExtra("pinNoteText", note);						

			if (action.contentEquals(ACTION_CREATE)) {			

				int longitude = this.getIntent().getIntExtra("longitude", -1);
				int latitude = this.getIntent().getIntExtra("latitude", -1);
				
				intent.putExtra("action", ACTION_CREATE);
				intent.putExtra("longitude", longitude);
				intent.putExtra("latitude", latitude);			
				
			} else if(action.contentEquals(ACTION_EDIT)) {
								
				int pointIndex = this.getIntent().getIntExtra("pointIndex", -1);
				
				intent.putExtra("action", ACTION_EDIT);				
				intent.putExtra("pointIndex", pointIndex);				
			}

			this.setResult(RESULT_OK, intent);

		} else if (v == findViewById(R.id.DeletePinButton)) {

			Intent intent = new Intent();

			if (this.getIntent().hasExtra("pointIndex")) {
				int pointIndex = this.getIntent().getIntExtra("pointIndex", -1);
				intent.putExtra("pointIndex", pointIndex);				
			}

			this.setResult(RESULT_CANCELED, intent);

		}

		finish();
	}
}
